package com.yuesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuesystem.common.BaseContext;
import com.yuesystem.common.CustomException;
import com.yuesystem.dto.responsebody.BrowseHistoryResponseBody;
import com.yuesystem.entity.Blog;
import com.yuesystem.entity.BrowseHistory;
import com.yuesystem.entity.User;
import com.yuesystem.mapper.BrowseHistoryMapper;
import com.yuesystem.service.BlogService;
import com.yuesystem.service.BrowseHistoryService;
import com.yuesystem.service.UserService;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 浏览记录接口实现类.
 */
@Service
@Slf4j
public class BrowseHistoryServiceImpl extends
    ServiceImpl<BrowseHistoryMapper, BrowseHistory> implements BrowseHistoryService {

  @Autowired
  private UserService userService;

  @Autowired
  private BlogService blogService;

  /**
   * 前台返回帖子id,记录用户浏览记录.
   *
   * @param blogId 帖子id
   */
  @Override
  public void currentBrowse(Long blogId) {
    BrowseHistory browseHistory = new BrowseHistory();
    Long userId = BaseContext.getCurrentId();
    LocalDateTime localDateTime = LocalDateTime.now();
    LambdaQueryWrapper<BrowseHistory> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(BrowseHistory::getUserId, userId)
        .eq(BrowseHistory::getBlogId, blogId);
    List<BrowseHistory> historyList = this.list(queryWrapper);
    if (historyList.size() == 0) {
      //createTime全局，自动填充
      browseHistory.setUserId(userId);
      browseHistory.setBlogId(blogId);
      browseHistory.setUpdateTime(LocalDateTime.now());
      this.save(browseHistory);
    } else {
      DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
      String localTime = df.format(localDateTime);
      String[] strArray = localTime.split(" ");
      String startTime = strArray[0] + " 00:00:00";
      String endTime = strArray[0] + " 23:59:59";
      LocalDateTime start = LocalDateTime.parse(startTime, df);
      LocalDateTime end = LocalDateTime.parse(endTime, df);
      LambdaQueryWrapper<BrowseHistory> queryWrapper1 = new LambdaQueryWrapper<>();
      queryWrapper1.eq(BrowseHistory::getBlogId, blogId)
          .eq(BrowseHistory::getUserId, userId)
          .ge(BrowseHistory::getCreateTime, start)
          .le(BrowseHistory::getCreateTime, end);
      BrowseHistory one = this.getOne(queryWrapper);
      if (one == null) {
        browseHistory.setUserId(userId);
        browseHistory.setBlogId(blogId);
        browseHistory.setUpdateTime(LocalDateTime.now());
        this.save(browseHistory);
      } else {
        one.setUpdateTime(localDateTime);
        this.updateById(one);
      }
    }
  }

  /**
   * 后台获取当前用户的所有的浏览记录.
   *
   * @return 浏览历史响应类
   */
  public List<BrowseHistoryResponseBody> browseHistory() {
    Long currentId = BaseContext.getCurrentId();
    LambdaQueryWrapper<BrowseHistory> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(BrowseHistory::getUserId, currentId);
    queryWrapper.orderByDesc(BrowseHistory::getUpdateTime);
    List<BrowseHistory> browseHistoryList = this.list(queryWrapper);
    if (browseHistoryList.size() == 0) {
      throw new CustomException("暂时还没有浏览记录");
    } else {
      List<BrowseHistoryResponseBody> dtoList = browseHistoryList.stream().map((item) -> {
        BrowseHistoryResponseBody browseHistoryResponseBody = new BrowseHistoryResponseBody();
        BeanUtils.copyProperties(item, browseHistoryResponseBody);
        Long blogId = item.getBlogId();
        Blog blog = blogService.getById(blogId);
        String title = blog.getTitle();
        Long userId = blog.getUserId();
        User one = userService.getById(userId);
        String userName = one.getUserName();
        String img = one.getImg();
        if (item != null) {
          browseHistoryResponseBody.setTitle(title);
          browseHistoryResponseBody.setAuthorName(userName);
          browseHistoryResponseBody.setImg(img);
        }
        return browseHistoryResponseBody;
      }).collect(Collectors.toList());
      return dtoList;
    }
  }

  /**
   * 根据blog的id删除所有和他有关的浏览记录.
   *
   * @param listBlog 帖子id列表
   */
  @Override
  public void deleteByBlog(List<Long> listBlog) {
    LambdaQueryWrapper<BrowseHistory> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.in(listBlog.size() != 0, BrowseHistory::getBlogId, listBlog);
    this.remove(queryWrapper);
  }
}
